package com.golddaymicromall.activity.recharge;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.BankInfo;
import com.golddaymicromall.util.DatePickDialogUtil;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.golddaymicromall.util.TimePickDialogUtil;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.android.schedulers.AndroidSchedulers;

public class RemittanceRegAddActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mRemitReg_back;
    private TextView mRemitReg_random;
    private TextView mRemitReg_CustomerNo;
    private Spinner mRemitReg_MoneyType;
    private Spinner mRemitReg_BankName;
    private EditText mRemitReg_BankLast5;
    private Spinner mRemitReg_Currency;
    private EditText mRemitReg_MoneyNum;
    private EditText mRemitReg_Date;
    private EditText mRemitReg_Time;
    private EditText mRemitReg_Phone;
    private EditText mRemitReg_Note;
    private List<String> listBank;
    private String randomNum;
    private String customerNo;
    private String bankId;
    private String moneyType;
    private String bankLast5;
    private String currency;
    private String moneyNum;
    private String remittanceDate;
    private String phone;
    private String notes;
    private Button mRemitReg_Confirm;

    List<BankInfo> bankInfo = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remittance_reg_add);
        customerNo = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
        initView();
        adapterForSpinner();
        attemptBackInfo();
    }

    public void initView() {
        mRemitReg_back = (LinearLayout) findViewById(R.id.remitReg_back);
        mRemitReg_random = (TextView) findViewById(R.id.remitreg_random);
        mRemitReg_CustomerNo = (TextView) findViewById(R.id.remitreg_customerNo);
        mRemitReg_MoneyType = (Spinner) findViewById(R.id.remitreg_moneytype);
        mRemitReg_BankName = (Spinner) findViewById(R.id.remitreg_bankname);
        mRemitReg_BankLast5 = (EditText) findViewById(R.id.remitreg_banklast5);
        mRemitReg_Currency = (Spinner) findViewById(R.id.remitreg_currency);
        mRemitReg_MoneyNum = (EditText) findViewById(R.id.remitreg_moneyNum);
        mRemitReg_Date = (EditText) findViewById(R.id.remitreg_date);
        mRemitReg_Time = (EditText) findViewById(R.id.remitreg_time);
        mRemitReg_Phone = (EditText) findViewById(R.id.remitreg_phone);
        mRemitReg_Note = (EditText) findViewById(R.id.remitreg_note);
        mRemitReg_Confirm = (Button) findViewById(R.id.remitreg_addConfirm);
        mRemitReg_random.setText(Random());

        mRemitReg_Date.setText(getCurrentDate());
        mRemitReg_Time.setText(getCurrentTime());
        mRemitReg_CustomerNo.setText(customerNo);
        mRemitReg_back.setOnClickListener(this);
        mRemitReg_Confirm.setOnClickListener(this);

        try {
            mRemitReg_Date.setOnClickListener(v -> {
                DatePickDialogUtil datePicKDialog = new DatePickDialogUtil(
                        RemittanceRegAddActivity.this, getCurrentDate());
                datePicKDialog.datePicKDialog(mRemitReg_Date);
            });
            mRemitReg_Time.setOnClickListener(v -> {
                TimePickDialogUtil timePicKDialog = new TimePickDialogUtil(
                        RemittanceRegAddActivity.this, getCurrentTime());
                timePicKDialog.timePicKDialog(mRemitReg_Time);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void adapterForSpinner() {
        List listMoneyType = new ArrayList();
        listMoneyType.add("现金");
        ArrayAdapter<String> moneyTypeAdapter = new ArrayAdapter<String>(RemittanceRegAddActivity.this, android.R.layout.simple_spinner_dropdown_item, listMoneyType);
        mRemitReg_MoneyType.setAdapter(moneyTypeAdapter);
        mRemitReg_MoneyType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                Spinner spinner = (Spinner) parent;
                moneyType = spinner.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(getApplicationContext(), "没有改变的处理",
                        Toast.LENGTH_LONG).show();
            }
        });

        List listCurrency = new ArrayList();
        listCurrency.add("人民币");
        ArrayAdapter<String> currentyAdapter = new ArrayAdapter<String>(RemittanceRegAddActivity.this, android.R.layout.simple_spinner_dropdown_item, listCurrency);
        mRemitReg_Currency.setAdapter(currentyAdapter);
        mRemitReg_Currency.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                Spinner spinner = (Spinner) parent;
                currency = spinner.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(getApplicationContext(), "没有改变的处理",
                        Toast.LENGTH_LONG).show();
            }
        });

    }

    //获取随机数
    public String Random() {
        int random = (int) ((Math.random() * 9 + 1) * 10000);
        return String.valueOf(random);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.remitReg_back:
                finish();
                break;
            case R.id.remitreg_addConfirm:
                attemptRemittanceRegAdd();
                break;
        }
    }

    public void attemptBackInfo() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.dictionnary.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("parentid", "535");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(RemittanceRegAddActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(RemittanceRegAddActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            bankInfo = JSON.parseArray(result, BankInfo.class);
                            listBank = new ArrayList<String>();
                            for (int i = 0; i < bankInfo.size(); i++) {
                                listBank.add(bankInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(RemittanceRegAddActivity.this, android.R.layout.simple_spinner_dropdown_item, listBank);
                            mRemitReg_BankName.setAdapter(arrayAdapter);
                            for (int i = 0; i < listBank.size(); i++) {
                                if ("请选择".equals(listBank.get(i))) {
                                    mRemitReg_BankName.setSelection(i);
                                }
                            }
                            mRemitReg_BankName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < bankInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(bankInfo.get(i).getName())) {
                                            bankId = bankInfo.get(i).getTextvalue();
                                            mRemitReg_BankLast5.setText(bankInfo.get(i).getBankno());
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }

                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    public void attemptRemittanceRegAdd() {
        customerNo = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
        randomNum = mRemitReg_random.getText().toString();
        bankLast5 = mRemitReg_BankLast5.getText().toString();
        moneyNum = mRemitReg_MoneyNum.getText().toString();
        phone = mRemitReg_Phone.getText().toString();
        notes = mRemitReg_Note.getText().toString();
        remittanceDate = mRemitReg_Date.getText().toString() + "，" + mRemitReg_Time.getText().toString();
        if (bankId.equals("0")) {
            Toast.makeText(this, "请选择银行", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isNumber(bankLast5)) {
            Toast.makeText(this, "公司账号尾号必须为数字", Toast.LENGTH_SHORT).show();
            return;
        } else if ("".equals(bankLast5)) {
            Toast.makeText(this, "公司账号尾号不能为空", Toast.LENGTH_SHORT).show();
            return;
        } else if (bankLast5.length() != 5) {
            Toast.makeText(this, "公司账号尾号为5位，请您重新检查", Toast.LENGTH_SHORT).show();
            return;
        }
        if (moneyNum.contains("-")) {
            Toast.makeText(this, "汇款金额不能是负数", Toast.LENGTH_SHORT).show();
            return;
        } else if ("".equals(moneyNum)) {
            Toast.makeText(this, "汇款金额不能为空", Toast.LENGTH_SHORT).show();
            return;
        } else if (!isMoney(moneyNum)) {
            Toast.makeText(this, "请输入正确金额", Toast.LENGTH_SHORT).show();
            return;
        } else if (Float.parseFloat(moneyNum) < 0.001) {
            Toast.makeText(this, "汇款金额不能小于0.01", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(mRemitReg_Date.getText().toString())) {
            Toast.makeText(this, "汇款日期不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(mRemitReg_Time.getText().toString())) {
            Toast.makeText(this, "汇款时间不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isNumber(phone)) {
            Toast.makeText(this, "手机号必须为数字", Toast.LENGTH_SHORT).show();
            return;
        } else if ("".equals(phone)) {
            Toast.makeText(this, "联系电话不能为空", Toast.LENGTH_SHORT).show();
            return;
        } else if (!isphone(phone)) {
            Toast.makeText(this, "请输入有效的电话号码", Toast.LENGTH_SHORT).show();
            return;
        } else if (phone.length() != 11) {
            Toast.makeText(this, "请输入11位有效电话号码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isSpecial(notes)) {
            Toast.makeText(this, "备注不允许使用特殊字符", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.remittanceregister.add");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("serialnumber", randomNum);
        form.put("customerno", customerNo);
        form.put("fundcategory", moneyType);
        form.put("exchangebank", bankId);
        form.put("tailnumber", bankLast5);
        form.put("currency", currency);
        form.put("remittancemoney", moneyNum);
        form.put("datestr", remittanceDate);
        form.put("telephone", phone);
        form.put("memo", notes);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();
                    if (result.equals("1")) {
                        Toast.makeText(getApplicationContext(), "登记成功", Toast.LENGTH_SHORT).show();
                        MyApplication.getInstance().attemptRiZhi(customerNo, "支付宝支付");
                        finish();
                    } else {
                        Toast.makeText(getApplicationContext(), "登记失败", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    public boolean isMoney(String Num) {
        Pattern p = Pattern
                .compile("^(([1-9]\\d{0,9})|0)(\\.\\d{1,2})?$");
        Matcher m = p.matcher(Num);
        return m.matches();
    }

    public boolean isNumber(String Num) {
        Pattern p = Pattern
                .compile("^[0-9]*$");
        Matcher m = p.matcher(Num);
        return m.matches();
    }

    public boolean isphone(String Num) {
        Pattern p = Pattern
                .compile("^1[3|4|5|7|8][0-9]\\d{8}$");
        Matcher m = p.matcher(Num);
        return m.matches();
    }

    public boolean isSpecial(String bz) {
        String regEx = "[`~!@#$%^&*()+=|{}':;'\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(bz);
        return m.find();
    }

    //获取当前日期
    public String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new java.util.Date());
        return date;
    }

    //获取当前时间
    public String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String time = sdf.format(new java.util.Date());
        return time;
    }

}
